package site.jlopen.assets.shiro.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;

import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import site.jlopen.utils.http.BrowserUtil;

public class WebAuthenticationFilter extends FormAuthenticationFilter {
	
	private static final String USR_LOGIN_URL = "/login";

	//@Value("${wites.include}")
	//private String[] shiroWites;
    
	private List<String> wites(){
		List<String> list = new ArrayList<String>();
		list.add("/login");
		list.add("/logon");
		list.add("/register");
		list.add("/error");
		list.add("/plug/**");
		list.add("/base/**");
		list.add("/favicon.ico");
		list.add("/doc.html");
		list.add("/swagger-ui.html");
	    return list;
	}
	
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    	HttpServletRequest hsRequest = (HttpServletRequest) request;
        HttpServletResponse hsResponse = (HttpServletResponse) response;
        String url = hsRequest.getRequestURI();
        //if(null != shiroWites) {
        	for (String shiroWite : wites()) {
        		 if(url.indexOf(shiroWite) >= 0) {
        			 return true;
        		 }
			}
        //}
     	Subject subject = SecurityUtils.getSubject();
     	if (null != subject.getPrincipal() && subject.isAuthenticated()) {
     		return true;
     	}
     	boolean isAjaxRequest = BrowserUtil.isAjax(hsRequest);
        if (isAjaxRequest) {
            //hsResponse.setHeader("sessionstatus", "TIMEOUT");
            //hsResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            hsResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        } else {
            hsResponse.sendRedirect(USR_LOGIN_URL);
        }
        return false;
    }


    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException{

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String url = httpServletRequest.getRequestURI();

        //if(url.contains("/admin") || url.contains("/admin/")) {
        	//WebUtils.issueRedirect(request, response, ADMIN_LOGIN_URL);
        //}else {
        	WebUtils.issueRedirect(request, response, USR_LOGIN_URL);
        //}
    }
}
